let payAcctDao = require("../dao/payAcctDao");
let payAcctAlterDao = require("../dao/payAcctAlterDao");
let redis = require('../dao/redis');
let payAcctService = module.exports;

payAcctService.alter = async function (acct) {
    let lockKey = "pay:acct:alter:" + acct.uid + "_" + acct.type + "_" + acct.acct;
    let isSucc = await redis.lock(lockKey, 1, 5);
    if (!isSucc) {
        console.logw("alter limit:", lockKey);
        return -1;
    }

    let cacheKey = "pay:acct:get:" + acct.uid;
    let acctRes = await payAcctDao.get(acct);
    if (!acctRes) {
        if (!acct.realName || acct.realName === ""){
            console.logw("real name is null");
            throw "real name is null";
        }

        /*
        uid
        type
        oldAcct
        newAcct
         */
        let alter = {
            uid: acct.uid,
            type: acct.type,
            oldAcct: acct.acct,
            newAcct: acct.acct,
            oldRealName: acct.realName
        };
        await payAcctAlterDao.save(alter);
        let res = await payAcctDao.save(acct);
        if (res > 0) redis.del(cacheKey);
        return res;
    } else {
        let alter = {
            uid: acct.uid,
            type: acct.type,
            oldAcct: acctRes.acct_no,
            newAcct: acct.acct,
            oldRealName: acctRes.realname
        };
        await payAcctAlterDao.save(alter);
        let res = await payAcctDao.update(acct);
        if (res > 0) redis.del(cacheKey);
        return res;
    }
};

payAcctService.getAcct = async function (uid) {
    let cacheKey = "pay:acct:get:" + uid;
    let result = await redis.get(cacheKey);
    if (!result) {
        let alipayAcct = await payAcctDao.get({uid: uid, type: "A0000"});
        let bankCardAcct = await payAcctDao.get({uid: uid, type: "B0000"});

        result = {ali: alipayAcct, bnk: bankCardAcct};
        await redis.set(cacheKey, result, 600);
    }

    return result;
};

